package com.lemon.components.wechart;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WechartBase {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	protected String getCommand(String url) {
		logger.info("[微信]发送GET命令地址：{}", url);
		StringBuilder sb = new StringBuilder();
		try {
			URLConnection connection = new URL(url).openConnection();
			connection.connect();
			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String temp;
			while ((temp = br.readLine()) != null) {
				sb.append(temp);
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("[微信]发送GET命令返回结果：{}", sb.toString());
		return sb.toString();
	}

	protected String postCommand(String url, String commond) {
		logger.info("[微信]发送POST命令地址：{}，发送命令参数：{}", url, commond);

		CloseableHttpClient httpClient = HttpClients.createDefault();

		HttpPost post = new HttpPost(url);
		if (!StringUtils.isBlank(commond)) {
			StringEntity params = new StringEntity(commond, "UTF-8");
			post.setEntity(params);
		}
		try {

			HttpResponse response = httpClient.execute(post);
			HttpEntity entity = response.getEntity();
			String temp = EntityUtils.toString(entity);
			logger.info("[微信]发送POST命令返回结果：{}", temp);
			return temp;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	public String upload(String url, String name, InputStream is) {

		HttpURLConnection con = null;
		try {
			URL urlObj = new URL(url);
			con = (HttpURLConnection) urlObj.openConnection();
		} catch (Exception e1) {
			e1.printStackTrace();
			return null;
		}
		// 连接
		String result = null;
		con.setDoInput(true);

		con.setDoOutput(true);

		con.setUseCaches(false); // post方式不能使用缓存

		// 设置请求头信息
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");
		// 设置边界
		String BOUNDARY = "----------" + System.currentTimeMillis();
		con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

		// 请求正文信息
		// 第一部分：
		StringBuilder sb = new StringBuilder();
		sb.append("--"); // 必须多两道线
		sb.append(BOUNDARY);
		sb.append("\r\n");
		try {
			sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + is.available() + "\";filename=\""	+ name + "\"\r\n");
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		sb.append("Content-Type:application/octet-stream\r\n\r\n");
		try {
			byte[] head = sb.toString().getBytes("utf-8");
			// 获得输出流
			BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream());
			// 输出表头
			out.write(head);

			// 文件正文部分
			// 把文件已流文件的方式 推入到url中
			BufferedInputStream in = new BufferedInputStream(is);
			int bytes = 0;
			byte[] bufferOut = new byte[1024];
			while ((bytes = in.read(bufferOut)) != -1) {
				out.write(bufferOut, 0, bytes);
			}
			in.close();
			// 结尾部分
			byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
			out.write(foot);
			out.flush();
			out.close();
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		try {
			// 定义BufferedReader输入流来读取URL的响应
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			if (result == null) {
				result = buffer.toString();
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
					return null;
				}
			}
		}
		logger.info("[微信]上传文件返回结果：{}", result);
		return result;
	}
}
